/**
 * 存储localStorage
 */
export const setStore = (name, content) => {
  if (!name) return;
  if (typeof content !== 'string') {
    content = JSON.stringify(content);
  }
  window.localStorage.setItem(name, content);
}

/**
 * 获取localStorage
 */
export const getStore = name => {
  if (!name) return;
  return window.localStorage.getItem(name);
}

/**
 * 删除localStorage
 */
export const removeStore = name => {
  if (!name) return;

  window.localStorage.removeItem(name);
}

/**
 * 存储sessionStorage
 */
export const setSessionStore = (name, content) => {
  if (!name) return;
  if (typeof content !== 'string') {
    content = JSON.stringify(content);
  }
  window.sessionStorage.setItem(name, content);
}

/**
 * 获取sessionStorage
 */
export const getSessionStore = name => {
  if (!name) return;
  return window.sessionStorage.getItem(name);
}

/**
 * 删除sessionStorage
 */
export const removeSessionStore = name => {
  if (!name) return;
  window.sessionStorage.removeItem(name);
}

/**
 * 获取style样式
 */
export const getStyle = (element, attr, NumberMode = 'int') => {
  let target;
  // scrollTop 获取方式不同，没有它不属于style，而且只有document.body才能用
  if (attr === 'scrollTop') {
    target = element.scrollTop;
  } else if (element.currentStyle) {
    target = element.currentStyle[attr];
  } else {
    target = document.defaultView.getComputedStyle(element, null)[attr];
  }
  //在获取 opactiy 时需要获取小数 parseFloat
  return NumberMode == 'float' ? parseFloat(target) : parseInt(target);
}

/**
 * 截取请求链接上参数(http://192.168.1.108:8080/bluehired/login.html?identity=45670b55437d4cbd920504d296fd3398)
 * @param {Object} param 如identity
 */
export function getParam(param) {
  //获取当前URL
  var local_url = document.location.href;
  //获取要取得的get参数位置
  var get = local_url.indexOf(param + "=");
  if (get == -1) {
    return null;
  }
  //截取字符串
  var get_par = local_url.slice(param.length + get + 1);
  //判断截取后的字符串是否还有其他get参数
  var nextPar = get_par.indexOf("&");
  if (nextPar != -1) {
    get_par = get_par.slice(0, nextPar);
  }
  return get_par;
}

/**
 * 获取普通js连接参数
 * @param name
 * @returns {string | null}
 */
export function getUrlKey(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) || [, ""])[1].replace(/\+/g, '%20')) || null
}

/**
 * 制保留2位小数，如：2会在后面补上00，即2.00
 * @param {Object} number 数字
 */
export function toDecimal(number) {
  var f = parseFloat(number);
  if (isNaN(f)) {
    return false;
  }
  var f = Math.round(number * 100) / 100;
  var s = f.toString();
  var rs = s.indexOf('.');
  if (rs < 0) {
    rs = s.length;
    s += '.';
  }
  while (s.length <= rs + 2) {
    s += '0';
  }
  return s;
}

/**
 * 格式化时间
 * @param date
 * @param fmt
 * @returns {*}
 */
export function formatDate(date, fmt) {
  //匹配年字符串，若可以匹配，则执行替换
  if (/(y+)/.test(fmt)) {
    //将yyyy替换为真实年份，substr是为了年份可以以不同长度显示
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '')).substr(4 - RegExp.$1.length);
  }
  let o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  //遍历匹配月、日、时、分、秒，并替换
  for (let k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      let str = o[k] + '';
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str));
    }
  }
  return fmt;
}

//数字为单数时，在前面补零
function padLeftZero(str) {
  return ('00' + str).substr(str.length);
}

/**
 * 获取当前缩放比
 * @returns {number}
 */
export function getDeviceRatio() {
  var isAndroid = window.navigator.appVersion.match(/android/gi);
  var isIPhone = window.navigator.appVersion.match(/iphone/gi);
  var devicePixelRatio = window.devicePixelRatio;
  var dpr;
  if (isIPhone) {
    // iOS下，对于2和3的屏，用2倍的方案，其余的用1倍方案
    if (devicePixelRatio >= 3) {
      dpr = 3;
    } else if (devicePixelRatio >= 2) {
      dpr = 2;
    } else {
      dpr = 1;
    }
  } else {
    // 其他设备下，仍旧使用1倍的方案
    dpr = 1;
  }
  return dpr
}

/**
 * 压缩照片成Base64
 * @param file
 * @param callback
 */
export function getBase64(file, callback) {
  var maxWidth = 640;
  if (file.files && file.files[0]) {
    var thisFile = file.files[0];
    if (thisFile.size > 4038400) {
      this.$vux.toast.text("图片不能超过4M", "middle");
      return
    }
    var reader = new FileReader();
    reader.onload = function (event) {
      var imgUrl = event.target.result;
      var img = new Image();
      img.onload = function () {
        var canvasId = 'canvasBase64Imgid',
          canvas = document.getElementById(canvasId);
        if (canvas != null) {
          document.body.removeChild(canvas);
        }
        var canvas = document.createElement("canvas");
        canvas.innerHTML = 'New Canvas';
        canvas.setAttribute("id", canvasId);
        canvas.style.display = 'none';
        document.body.appendChild(canvas);
        canvas.width = this.width;
        canvas.height = this.height;
        var imageWidth = this.width,
          imageHeight = this.height;
        if (this.width > maxWidth) {
          imageWidth = maxWidth;
          imageHeight = this.height * maxWidth / this.width;
          canvas.width = imageWidth;
          canvas.height = imageHeight;
        }
        var context = canvas.getContext('2d');
        context.clearRect(0, 0, imageWidth, imageHeight);
        context.drawImage(this, 0, 0, imageWidth, imageHeight);
        var base64 = canvas.toDataURL('image/png', 1);
        var imgbase = base64.substr(22);
        callback(imgbase)
      }
      img.src = imgUrl;
    }
    reader.readAsDataURL(file.files[0]);
  }
}

/**
 * 将base64转换为文件对象
 * @param base64字符串
 * @returns {Blob}
 */
export function convertBase64ToBlob(base64) {
  var base64Arr = base64.split(',');
  var imgtype = '';
  var base64String = '';
  if (base64Arr.length > 1) {
    //如果是图片base64，去掉头信息
    base64String = base64Arr[1];
    imgtype = base64Arr[0].substring(base64Arr[0].indexOf(':') + 1, base64Arr[0].indexOf(';'));
  }
  // 将base64解码
  var bytes = atob(base64String);
  //var bytes = base64;
  var bytesCode = new ArrayBuffer(bytes.length);
  // 转换为类型化数组
  var byteArray = new Uint8Array(bytesCode);

  // 将base64转换为ascii码
  for (var i = 0; i < bytes.length; i++) {
    byteArray[i] = bytes.charCodeAt(i);
  }

  // 生成Blob对象（文件对象）
  return new Blob([bytesCode], {type: imgtype});
};

/**
 * 获取年月yyyy-mm
 */
export function getYearMonth() {
  var now = new Date();
  var time = now.getFullYear() + "-" + ((now.getMonth() + 1) < 10 ? "0" : "") + (now.getMonth() + 1);
  return time;
}

/**
 * 将个位数字变成两位
 */
export function doubleNum(num) {
  if (num < 10) {
    return "0" + num;
  } else {
    return num + "";
  }
}

/**
 * 获取手机设备类型
 */
export function getDevice() {
  let u = navigator.userAgent;
  if (u.indexOf('Android') > -1 || u.indexOf('Adr') > -1) {
    return "android";
  } else if (!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
    return "ios";
  }
}

/**
 * 获取年月日时分
 */
export function getNowFormatDate(id) {
  let seg = "-";
  let mark = "lp";
  let date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1;
  let day = date.getDate() < 10 ? ('0' + date.getDate()) : date.getDate();
  let hour = date.getHours() < 10 ? ('0' + date.getHours()) : date.getHours();
  let minute = date.getMinutes() < 10 ? ('0' + date.getMinutes()) : date.getMinutes();
  return year + seg + month + seg + day + seg + hour + seg + minute + seg + id + seg + mark;
}


/**
 * 获取上一个月
 * @date 格式为yyyy-mm的日期，如：2014-01
 */
export function getPreMonth(date) {
  let arr = date.split('-');
  let year = arr[0];//获取当前日期的年份
  let month = arr[1];//获取当前日期的月份
  let tempYear = year;
  let tempMonth = parseInt(month) - 1;
  if (tempMonth == 0) {
    tempYear = parseInt(tempYear) - 1;
    tempMonth = 12;
  }
  if (tempMonth < 10) {
    tempMonth = '0' + tempMonth;
  }
  return tempYear + '-' + tempMonth;
}

/**
 * 获取下一个月
 * @date 格式为yyyy-mm的日期，如：2014-01
 */
export function getNextMonth(date) {
  var arr = date.split('-');
  var year = arr[0]; //获取当前日期的年份
  var month = arr[1]; //获取当前日期的月份
  var tempYear = year;
  var tempMonth = parseInt(month) + 1;
  if (tempMonth == 13) {
    tempYear = parseInt(tempYear) + 1;
    tempMonth = 1;
  }
  if (tempMonth < 10) {
    tempMonth = '0' + tempMonth;
  }
  return tempYear + '-' + tempMonth;
}
